;
import express from "express";
import DB from "../lib/DBHelper";
import fs from "fs";//fileSystem
const routes = express.Router();
import jw from "jsonwebtoken";
//登陆接口
routes.post("/login", (req, res, next) => {
    let sql = "SELECT `uId`,`uname` FROM `userinfo` WHERE uname=? AND upwd=?";
    let params = [req.body.uname, req.body.upwd];
    var resObj = { "msg": "登录失败", "status": -1 }
    DB.query(sql, params).then((data) => {
        console.log(data)
        if (data.length > 0) {
            //生成token口令;
            // var token=jw.sign(result[0],"kazoo.cn",{
            //     expiresIn:60*30
            // });
            resObj.data = data[0];
            resObj.msg = "登陆成功";
            resObj.status = 1;
        //    resObj.token=token;
        } else {
            resObj.data = data[0];
            resObj.msg = "登陆失败";
            resObj.status = -1;
        }
        res.json(resObj);
    }).catch((err) => {
        console.log(err);
        resObj.msg = "登录失败";
        resObj.err = err;
        res.json(resObj);
    });
});
//注册接口
routes.post("/reg", (req, res, next) => {
    let sql = "INSERT INTO `userinfo` (`uname`,`upwd`) VALUES (?,?)";
    let params = [req.body.uname, req.body.upwd];
    DB.query(sql, params).then((data) => {
        if (data.affectedRows == 1) {
            res.json({
                "msg": "注册成功",
                "status": 1
            })
        } else {
            res.json({
                "msg": "注册失败",
                status: -1
            })
        }
    }).catch((err) => {
        res.json({
            "msg": "注册失败",
            "status": -2,
            err
        })
    })
})
//检查是否用户重复
routes.post("/isuname", (req, res, next) => {
    let sql = "SELECT COUNT(*) AS COUNT FROM `userinfo` WHERE `uname`=?";
    let params = [req.body.uname];
    DB.query(sql, params).then((data) => {
        if (data[0].COUNT >= 1) {
            res.json({
                "msg": "用户已存在",
                status: -1
            })
        } else {
            res.json({
                "msg": "用户名可注册",
                status: 1
            })
        }
    })
})
//商品列表接口
routes.get("/goods", (req, res, next) => {
    //readfile 异步,不会阻塞
    //readfileSync 同步,会阻塞
    //读取json文件
    // let goodsStr=fs.readFile("../data/goodList.json",function (err,data) {
    //     console.log(data);
    // })//异步需要通过回调函数来获得数据
    let goodsStr = fs.readFileSync("./data/goodList.json", {
        encoding: "utf-8",
        flag: "r"
    });
    const tmpPid = req.query.pid == undefined ? 0 : req.query.pid;
    let goodsList = JSON.parse(goodsStr);
    var queryList = goodsList.filter((el) => {
        return el.pid.indexOf(tmpPid) != -1
    })
    if (req.query.pid == undefined) {
        res.json(goodsList)
    } else {
        res.json(queryList)
    }
})
//加入购物车
routes.post("/addCart", async(req, res, next) => {
    //查询语句
    let querysql = "SELECT * FROM `carts` WHERE `uid`=? AND `pid`=?  AND `pSize`=?";
    let queryparams = [req.body.uid, req.body.pid,req.body.pSize];
    let queryData =await DB.queryAsync(querysql, queryparams);
    if(queryData.length>=1){
         //  //修改
         let updatesql = "UPDATE `carts` SET `pNum`=pNum+?,`pTotal`=`pNum`*`pPrice` WHERE `uid`=? AND `pid`=?";
         let updateparm = [req.body.pNum,req.body.uid, req.body.pid];
         let updateData =await DB.queryAsync(updatesql, updateparm);
         console.log(updateData)
         if(updateData.affectedRows>=1){
             res.json({"msg":"加入成功","status":1});
         }else{
             res.json({"msg":"加入失败","status":-1});
         }
    }else{
          //  //插入语句
          let insersql = "INSERT INTO `carts` (`uid`,`pid`,`pName`,`pPrice`,`pNum`,`pTotal`,`pImg`,`pSize`)VALUES(?,?,?,?,?,?,?,?)";
          let inserparams = [
              req.body.uid,
              req.body.pid,
              req.body.pName,
              req.body.pPrice,
              req.body.pNum,
              req.body.pTotal,
              req.body.pImg,
              req.body.pSize,
          ];
          let inserData =await DB.queryAsync(insersql, inserparams);
          if(inserData.affectedRows>=1){
            res.json({"msg":"修改成功","status":2});
        }else{
            res.json({"msg":"修改失败","status":-2});
        }
    }

})
// 查询当前登陆者的购物车信息
routes.get("/getcarts",async (req,res,next)=>{
    let getDaSql="SELECT * FROM `carts` WHERE `uid`=?";
    let getDparams=[req.query.uid];
    const result=await DB.query(getDaSql,getDparams);
    res.json(result);
})
//修改购物车的数量价钱
routes.post("/modify",async (req,res,next)=>{
    let mfysql="UPDATE `carts` SET `pNum`=?,`pTotal`=`pNum`*`pPrice` WHERE `uid`=? AND `pid`=? AND `pSize`=?"
    let mfyparams=[req.body.pNum,req.body.uid,req.body.pid,req.body.pSize];
    var mfyData=await DB.queryAsync(mfysql,mfyparams);
    res.json(mfyData)
})

//删除购物车商品数据
routes.post("/delete",async (req,res,next)=>{
    let delsql="DELETE FROM `carts` WHERE `cId`=? AND `uid`=? AND `pid`=?";
    let delparams=[req.body.cid,req.body.uid,req.body.pid];
    var delData=await DB.queryAsync(delsql,delparams);
    res.json(delData)
})

//暴露
module.exports = {
    routes
}

